﻿namespace PlugNT.Common.Http
{
    using System;
    using System.Text;
    using System.Web;

    public class DicModule : IHttpModule
    {
        private void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication) sender).Context;
            string reqrawurl = context.Request.RawUrl.ToLower();
            int windex = reqrawurl.IndexOf("?");
            int aindex = reqrawurl.IndexOf(".");
            bool fakeurl = false;
            if (aindex > 0)
            {
                if ((windex > 0) && (windex < aindex))
                {
                    fakeurl = true;
                }
            }
            else
            {
                fakeurl = true;
            }
            if (fakeurl)
            {
                string rightargs = "";
                if (windex > 0)
                {
                    rightargs = "&" + reqrawurl.Substring(windex + 1);
                    reqrawurl = reqrawurl.Substring(0, windex);
                }
                string[] arguments = reqrawurl.Trim(new char[] { '/' }).Split(new char[] { '/' });
                bool firstfalg = true;
                StringBuilder sbreurl = new StringBuilder("/Default.aspx");
                foreach (string s in arguments)
                {
                    string[] mas = s.Split(new char[] { '-' });
                    if (mas.Length == 2)
                    {
                        if (firstfalg)
                        {
                            sbreurl.Append("?" + mas[0] + "=" + mas[1]);
                            firstfalg = false;
                        }
                        else
                        {
                            sbreurl.Append("&" + mas[0] + "=" + mas[1]);
                        }
                    }
                }
                if (!firstfalg)
                {
                    context.RewritePath(sbreurl.ToString() + rightargs);
                }
            }
        }

        private void Application_EndRequest(object source, EventArgs e)
        {
        }

        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            application.EndRequest += new EventHandler(this.Application_EndRequest);
        }
    }
}

